package com.kitty.cross.login.service;

import com.kitty.common.utils.SpringUtils;
import com.kitty.cross.CrossServerConfig;
import com.kitty.cross.core.CrossDataPool;
import com.kitty.cross.core.CrossServer;
import com.kitty.cross.core.CrossTransportManager;
import com.kitty.cross.core.P_Cross;
import com.kitty.cross.core.callback.CReqCallBack;
import com.kitty.cross.core.callback.CallBackCommands;
import com.kitty.cross.core.client.C2SSessionPoolFactory;
import com.kitty.cross.core.client.CCSession;
import com.kitty.cross.login.cmessage.G2CLeaveCross;
import com.kitty.cross.login.model.CrossInfo;
import com.kitty.game.ServerService;
import com.kitty.game.gate.LoginAuth;
import com.kitty.game.role.model.Role;
import com.kitty.game.server.message.RespSwitchServer;
import com.kitty.game.utils.JsonUtils;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service
public class CrossService {

    private ConcurrentMap<Long, Role> crossPlayers = new ConcurrentHashMap<>();

    public void init() {
        try {
            int serverId = ServerService.serverId;
            P_Cross p_cross = CrossDataPool.getCrossServer(serverId);
            if (p_cross != null) {
                new CrossServer().start(p_cross.getRpcPort());
            }
        } catch (Exception e) {

            throw new RuntimeException();
        }
    }

    public void addCrossPlayer(Role role) {
        crossPlayers.put(role.getUid(), role);
    }

    /**
     * 退出跨服，返回自己的游戏服
     * @param role
     */
    public void backGameServer(Role role) {
        if (!SpringUtils.getBean(CrossServerConfig.class).isCenterServer()) {
            return;
        }
        CrossInfo crossInfo = role.getCrossInfo();
        int fromServer = crossInfo.getFromServer();
        P_Cross p_cross = CrossDataPool.getCrossServer(fromServer);
        String rpcHost = p_cross.getIp();
        //LoggerFunction.CROSS.getLogger().info("[{}]服玩家（{}[{}]）退出跨服", fromServer, role.getName(), role.getUid());

        LoginAuth loginAuth = new LoginAuth();
        CReqCallBack req = new CReqCallBack();
        req.setCmd(CallBackCommands.LOGOUT);
        req.addParam("auth", JsonUtils.object2String(loginAuth));
        req.addParam("account", role.getSid());

        CCSession session = C2SSessionPoolFactory.getInstance().borrowCrossSession();
        try {
            Message callBack = SpringUtils.getBean(CrossTransportManager.class).callBack(session, req);
            if (callBack != null) {
                G2CLeaveCross logoutCallback = (G2CLeaveCross) callBack;
                RespSwitchServer respSwitchServer = new RespSwitchServer();
                respSwitchServer.setResult((short) 1);
                respSwitchServer.setContent(rpcHost + "," + p_cross.getGamePort()
                        + "," + loginAuth.getAuthKey() + "," + loginAuth.getSeed() + "," + role.getName());

                MessagePusher.pushMessage(role, respSwitchServer);
            }
        } catch (Exception e) {
         //   LoggerUtils.error("", e);
        }
    }

    public Role getCrossPlayer(long uid) {
        return crossPlayers.get(uid);
    }
}
